using System;
using System.Collections.Generic;
using Iesi.Collections.Generic;
using System.Linq;

namespace NhibernateDemoCore
{
    public class Order
    {
        private ICollection<OrderLine> lines = new HashedSet<OrderLine>();

        public virtual Guid OrderNumber { get; private set; }
        public virtual Customer Customer { get; private set; }
        public virtual DateTime Date { get; private set; }

        public virtual IEnumerable<OrderLine> Lines
        {
            get { return lines; }
        }

        protected Order()
        {
        }

        internal Order(Customer customer)
        {
            Customer = customer;
            OrderNumber = Guid.Empty;
            Date = DateTime.Today;
        }

        public virtual void Add(string product)
        {
            lines.Add(new OrderLine(product));
            lines.First(l => l.Product == product).Quantity++;
        }

        public virtual void Remove(string product)
        {
            var line = lines.FirstOrDefault(l => l.Product == product);
            
            if (line == null) return;
            line.Quantity--;

            if (line.Quantity > 0) return;
            lines.Remove(line);
        }

        public virtual bool Equals(Order other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return other.OrderNumber == OrderNumber;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            return obj.GetType() == typeof (Order) && Equals((Order) obj);
        }

        public override int GetHashCode()
        {
            return OrderNumber.GetHashCode();
        }

        public static bool operator ==(Order left, Order right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(Order left, Order right)
        {
            return !Equals(left, right);
        }
    }
}